package com.njust.controller;

import com.njust.Util.AliOssUtil;
import com.njust.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * @version 1.0
 * @Author Imak
 * @Date 2024/11/10 16:42
 * @通用接口
 */
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传，{}",file);

        try {
            String originalFilename = file.getOriginalFilename();//原始文件名
            String extension=originalFilename.substring(originalFilename.lastIndexOf("."));//后缀，文件格式
            String objectName=UUID.randomUUID().toString()+extension;

            String filePath=aliOssUtil.upload(file.getBytes(),objectName);
            return Result.success(filePath,"文件上传成功");
        } catch (IOException e) {
            log.error("文件上传失败：{}",e);
        }
        return Result.error("文件上传失败");
    }
}
